package org.budo.dubbo.protocol.http.view.render.impl;

import org.budo.dubbo.protocol.http.exception.BudoRuntimeException;
import org.budo.dubbo.protocol.http.invocation.adapter.ProtocolRequest;
import org.budo.dubbo.protocol.http.invocation.adapter.ProtocolResponse;
import org.budo.dubbo.protocol.http.view.render.AbstractViewRender;
import org.springframework.util.Assert;

import com.alibaba.dubbo.rpc.Result;

/**
 * @author lmw
 */
public class RawViewRender extends AbstractViewRender {
    public static final RawViewRender INSTANCE = new RawViewRender();

    @Override
    public void renderView(ProtocolRequest protocolRequest, ProtocolResponse response, Object result) throws Throwable {
        Assert.notNull(result, "#18 result is null");

        if (!(result instanceof Result)) {
            String message = "#26 result.type=" + result.getClass() + ", protocolRequest=" + protocolRequest;
            throw new BudoRuntimeException(message);
        }

        Result resultEntity = (Result) result;
        if (resultEntity.hasException()) {
            String message = "#40 result.hasException, exception=" + resultEntity.getException() + ", protocolRequest=" + protocolRequest;
            throw new BudoRuntimeException(message);
        }

        Object resultValue = resultEntity.getValue();
        this.serializeAndWriteToResponse(protocolRequest, response, resultValue);
    }
}